/** 
 * ColorAction.java
 * @author Lex
 * 2007-8-27 ����08:14:02
 */
package fun.ui.canvas.control;

import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;

import javax.swing.JFileChooser;
import javax.swing.JInternalFrame;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;

import org.lex.swing.ActionBuilder;

import fun.ui.FunMainFrame;
import fun.ui.canvas.CanvasPane;

public class SaveAction extends ActionBuilder {
    protected FunMainFrame mainframe = null;
    private JInternalFrame parent = null;
    private CanvasPane canvas = null;

    public SaveAction(FunMainFrame mainframe, JInternalFrame parent, CanvasPane canvas) {
	super("Save...");
	this.mainframe = mainframe;
	this.parent = parent;
	this.canvas = canvas;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
	// /XXX JFileChooser����Ϊ��JInternalFrame��һ��
	JFileChooser fc = this.getFileChooser();
	int opt = fc.showSaveDialog(parent);
	if (JFileChooser.APPROVE_OPTION == opt) {
	    File file = fc.getSelectedFile();
	    dir = fc.getCurrentDirectory();
	    FileFilter filter = fc.getFileFilter();
	    String format = filter.getDescription().toLowerCase();
	    if (false == filter.accept(file))
		file = new File(dir, file.getName() + "." + format);
	    boolean returns = false;
	    try {
		returns = canvas.saveImage(file, format);
		if (false == returns)
		    this.showError("Unkown error happened");
	    } catch (IOException ex) {
		ex.printStackTrace();
		this.showError(ex.getLocalizedMessage());
	    }
	}
    }

    private File dir = new File(".");

    private JFileChooser getFileChooser() {
	JFileChooser fc = new JFileChooser(dir);
	// ֻ��ѡ���ļ�
	fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
	// ֻ��ѡһ��
	fc.setMultiSelectionEnabled(false);
	// ����ʾ"��������"
	fc.setAcceptAllFileFilterUsed(false);
	// ���filter
	// /XXX FileNameExtensionFilter ��getDescription() �е��ǿ����
	// /���磬JPEG�ļ�������Ӧ����: "JPEG(.jped .jpg)"
	fc.addChoosableFileFilter(new FileNameExtensionFilter("BMP", "bmp"));
	fc.addChoosableFileFilter(new FileNameExtensionFilter("JPEG", "jpep", "jpg"));
	fc.addChoosableFileFilter(new FileNameExtensionFilter("PNG", "png"));
	fc.addChoosableFileFilter(new FileNameExtensionFilter("GIF", "gif"));
	return fc;
    }

    private void showError(String msg) {
	JOptionPane.showInternalMessageDialog(parent, msg, "Failed to Save Image", JOptionPane.ERROR_MESSAGE);
    }
}
